package com.example.myapplication.ui.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.app.Fragment;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
;

import com.example.myapplication.R;
import com.example.myapplication.TextActivity;
import com.example.myapplication.dao.ConfirmDao;
import com.example.myapplication.dao.FindorSort;
import com.example.myapplication.entity.Book;
import com.example.myapplication.ui.dashboard.SortFragment;

import java.util.ArrayList;
import java.util.HashMap;

public class HomeFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View rootview=inflater.inflate(R.layout.fragment_home,null);
        TextView textView= rootview.findViewById(R.id.name);
        if(ConfirmDao.islogin)
        textView.setText("你好，"+ConfirmDao.username);else textView.setText("请登录");
        GridView gridView= (GridView)rootview.findViewById(R.id.bookShelf);
        if(FindorSort.collectedBook!=null){
            int size=FindorSort.collectedBook.size();
            HashMap<String,Object> map=null;
            ArrayList ListItems = new ArrayList<HashMap<String, Object>>();
            System.out.println(FindorSort.collectedBook.size());
            for (int i=0;i<size;i++){
                map= new HashMap<>();
                map.put("name",FindorSort.collectedBook.get(i).getName() );
                map.put("pic",FindorSort.collectedPic.get(i));
                ListItems.add(map);
            }
            SimpleAdapter adapter=new SimpleAdapter(getContext(),ListItems,R.layout.book_item,new String[]{"pic","name"},new int[]{R.id.img_icon,R.id.txt_icon});
            adapter.setViewBinder((view, data, textRepresentation) -> {
                if ((view instanceof ImageView) & (data instanceof Bitmap)) {
                    ImageView imageView = (ImageView) view;
                    Bitmap mBitmap = (Bitmap) data;
                    imageView.setImageBitmap(mBitmap);
                    return true;
                }
                return false;
            });
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener((parent, view, position, id) -> {
                Intent intent=new Intent(getContext(), TextActivity.class);
                intent.putExtra("id",FindorSort.collectedBook.get(position).getId());
                startActivity(intent);
            });

        }

        return rootview;
}}